package com.redlion.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import com.redlion.GameActivity;
import com.redlion.StartActivity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterUser extends AsyncTask<Void, Void, Void> {
	private Handler handler;
	private ProgressDialog dialog;
	private Context context;
	private String name;
	public static String URLbody = "http://kinderstadt.w1.ms5.eu/pdd/";
	public static final String registerURL = URLbody + "player/register";
	private static final String TAG = "Server";
	static HttpParams httpParameters = new BasicHttpParams();
	static int timeoutConnection = 100000;
	static int timeoutSocket = 200000;
	Message m = new Message();

	public RegisterUser(StartActivity startActivity, String playerName, Handler handler) {
		this.context = startActivity;
		this.handler = handler;
		this.name = playerName;
	}

	@Override
	protected void onPreExecute() {
		dialog = new ProgressDialog(context);
		dialog.setMessage("Registriere Spieler...");
		dialog.setIndeterminate(true);
		dialog.setOnCancelListener(new OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
				RegisterUser.this.cancel(true);
				Toast.makeText(context, "RegisterUser abgebrochen", Toast.LENGTH_SHORT).show();
			}
		});
		dialog.show();
	}

	@Override
	protected Void doInBackground(final Void... args) {
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
		HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
		HttpClient httpClient = new DefaultHttpClient(httpParameters);
		Log.i("Server", registerURL + "/" + name);
		HttpGet httpGet = new HttpGet(registerURL + "/" + Uri.encode(name));
		HttpResponse response;
		UserData sd = null;
		m.arg1=1;
		try {
			httpGet.addHeader("Content-type", "application/json");
			httpGet.addHeader("Accept", "application/json");
			response = httpClient.execute(httpGet);
			// TODO: HTTP-Status (z.B. 404) in eigener Anwendung verarbeiten.

			Log.i(TAG, response.getStatusLine().toString());
			HttpEntity entity = response.getEntity();

			if (entity != null) {

				InputStream instream = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
				StringBuilder sb = new StringBuilder();

				String line = null;
				while ((line = reader.readLine()) != null)
					sb.append(line);

				String result = sb.toString();
				Log.i(TAG, result);
				instream.close();

				JSONObject json = new JSONObject(result);
				JSONObject data = json.getJSONObject("player");
				
				if (data != null) {
					Log.i(TAG, data.toString());
					int id = data.getInt("id");
					int score = data.getInt("score");
					int rankting = data.getInt("ranking");
					int playtime = data.getInt("playtime");
					String name = data.getString("name");
					String location = data.getString("location");
					sd = new UserData(id, score, rankting, playtime, name, location);
				}
				m.obj = sd;
				m.arg1=0;
			}
		} catch (ClientProtocolException e) {
			m.arg1=1;
			Log.e("ClientProtocolException", e.getMessage());
		} catch (IOException e) {
			m.arg1=1;
			Log.e("IOException", e.getMessage());
		} catch (Exception e) {
			m.arg1=1;
			Log.e("Exception", e.getMessage());
		}
		return null;
	}

	@Override
	protected void onPostExecute(final Void unused) {
		handler.sendMessage(m);
		dialog.dismiss();
	}

}
